package com.headwind.async.controller;

import com.headwind.async.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

import static java.lang.Thread.sleep;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/9
 * @description : 执行任务控制类
 */
@RestController
public class AsyncController {

    /**
     * 注入Service类
     */
    @Autowired
    private AsyncService asyncService;

    /**
     * 调用任务Service类
     *
     * @return 执行结果
     * @throws InterruptedException
     */
    @GetMapping(value = "/async")
    public String asyncTest() throws InterruptedException {
        long start = System.currentTimeMillis();
        Future<String> task1 = asyncService.task1();
        Future<String> task2 = asyncService.task2();
        Future<String> task3 = asyncService.task3();
        while (!task1.isDone() || !task2.isDone() || !task3.isDone()) {
            sleep(1000);
        }
        return "所有任务执行结束，总耗时：" + (System.currentTimeMillis() - start) + "毫秒";
    }
}
